package VolumePartition;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

public class VolumePartitionReducer extends Reducer<Text, VolumePartitionFlowBean, Text, VolumePartitionFlowBean> {
    // 定义一个TreeMap作为存储数据的容器（按key排序）
    private TreeMap<VolumePartitionFlowBean, Text> flowMap = new TreeMap<>();

//    @Override
    protected void reduce(Text key, Iterable<VolumePartitionFlowBean> values, Reducer.Context context) throws IOException, InterruptedException {
        for (VolumePartitionFlowBean value :
                values) {
            VolumePartitionFlowBean flowBean = new VolumePartitionFlowBean(value.getSymbol(), value.getVolume());

//            Text phone = new Text(key);
            Text datetext = new Text(key);

//             1 向treeMap集合中添加数据
            flowMap.put(flowBean, datetext);
//            flowMap.put(value, key);

        }
    }

    @Override
    protected void cleanup(Reducer.Context context) throws IOException, InterruptedException {
        // 3 遍历集合，输出数据
        Iterator<VolumePartitionFlowBean> iterator = flowMap.keySet().iterator();

        while (iterator.hasNext()) {
            VolumePartitionFlowBean valueOut = iterator.next();
            Text keyOut = flowMap.get(valueOut);

            context.write(keyOut, valueOut);
        }

    }
}
